package com.xuanwei.web.interceptor;

import com.alibaba.fastjson.JSON;
import com.xuanwei.core.entity.bo.WxUserDetail;
import com.xuanwei.core.response.ResultVO;
import com.xuanwei.core.util.JwtTokenUtil;
import com.xuanwei.dao.entity.XwUser;
import com.xuanwei.xwcommon.consts.CacheName;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @Author jiangyong
 * @Description TODO
 * @Date 2019/4/18 14:25
 **/
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil tokenUtil;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String token = request.getHeader("token");
        if (token != null && !"undefined".equals(token)) {
            String id = tokenUtil.getUserNameFromToken(token);
            log.info("checking userId {}:", id);
            if (id != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                String tokenTemp = redisTemplate.opsForValue().get(CacheName.USER_TOKEN + id);
                if (tokenTemp == null || !tokenTemp.equals(token)) {
                    //对退出要保证code=2000,token正确时,退出删除redis,token;不正确也要退出,但要删除redis,token
                    if ("/api/admin/logout.do".equals(request.getRequestURI())) {
                        responseError(response, ResultVO.successResult("退出成功"));
                        return;
                    }
                    responseError(response, ResultVO.LoginFail());
                    return;
                }
                XwUser user = new XwUser();
                user.setId(Integer.parseInt(id));
                UserDetails userDetails = new WxUserDetail(user);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        filterChain.doFilter(request, response);
    }

    private void responseError(HttpServletResponse response, ResultVO resultVO) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().write(JSON.toJSONString(resultVO));
        response.getWriter().flush();
        response.getWriter().close();
    }
}
